<?php
/**
 * 交流部分
 * 
 * @package ews
 * @ews Enterprise WorkShop
 * @version 1.0 alpha
 * @since 2011-05-05
 * @author monkee
 */

class forumModel extends model
{
	public function create($subject, $user_id, $message = '', $attachment = 0){
		$id = DB::insert('forum', array(
			'subject' => $subject,
			'user_id' => $user_id,
			'message' => $message,
			'atta_count' => $attachment,
			'mktime' => TIMESTAMP,
		));
		if(!empty($message)){
			DB::insert('post', array(
				'message' => $message,
				'forum_id' => $id,
				'mktime' => TIMESTAMP,
				'user_id' => $user_id
			));
			DB::columnAdd('forum', 'post_count', 'forum_id = '.$id, 1);
		}
		return $id;
	}
	public function update($id, $message, $user_id){
		$message = trim($message);
		if(empty($message)){
			return;
		}
		DB::columnAdd('forum', 'post_count', 'forum_id = '.$id, 1);
		DB::update('forum', array(
			'message' => $message
		), "forum_id = {$id}");
		DB::insert('post', array(
			'message' => $message,
			'forum_id' => $id,
			'mktime' => TIMESTAMP,
			'user_id' => $user_id
		));
	}
	
	public function get_posts($forum_id){
		return DB::fetchArray('SELECT a.*, b.username FROM '.DB::table('post')." a LEFT JOIN ".DB::table('user')." b ON a.user_id = b.user_id WHERE forum_id = {$forum_id}");
	}
	public function get($forum_id){
		return DB::fetchOne('SELECT * FROM '.DB::table('forum')." WHERE forum_id = {$forum_id}");
	}
	public function search($key){
		if(empty($key)){
			return array();
		}
		$row = DB::fetchArray('SELECT a.*, b.username FROM '.DB::table('forum')." a LEFT JOIN ".DB::table('user')." b ON a.user_id = b.user_id WHERE subject = '".DB::escape_string($key)."'");
		return $row;
	}
	
	public function mulit_search($key){
		if(empty($key)){
			return array();
		}
		$row = DB::fetchArray('SELECT a.*, b.username FROM '.DB::table('forum')." a LEFT JOIN ".DB::table('user')." b ON a.user_id = b.user_id WHERE subject LIKE '%".DB::escape_string($key)."%'");
		return $row;
	}
	public function get_list(){
		return DB::fetchArray('SELECT a.*, b.username FROM '.DB::table('forum')." a LEFT JOIN ".DB::table('user')." b ON a.user_id = b.user_id ORDER BY forum_id DESC LIMIT 10");
	}
}
?>